<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
    :size="formSize"
    status-icon
  >
    <el-form-item label="分类名称" prop="name">
      <el-input v-model="ruleForm.name" />
    </el-form-item>
    <el-form-item label="父级类目" prop="parent">
      <el-select v-model="ruleForm.parent" placeholder="Activity zone">
        <el-option label="顶级类目" value="0-0" />
        <el-option
          v-for="item in category.parentList"
          :key="item.objectId"
          :label="item.name"
          :value="item.objectId"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="是否展示" prop="isShow">
      <el-switch
        v-model="ruleForm.isShow"
        inactive-value="2"
        active-value="1"
      />
    </el-form-item>
    <el-form-item label="分类图标" prop="icon">
      <el-input v-model="ruleForm.icon" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        Create
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { useCategory } from "../../store/category";
import { CategoryType } from "../../types/job";
import { categoryPost } from "../../api/job";
const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<Omit<CategoryType, "objectId">>({
  name: "",
  parent: "",
  isShow: "2", // 1代表可见，2代表不可见
  icon: "img.png",
});
type CateType = Omit<CategoryType, "children">;
const rules = reactive<FormRules<CateType>>({
  name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
  parent: [{ required: true, message: "请选择父级类目", trigger: "blur" }],
  isShow: [{ required: true, message: "请修改展示状态", trigger: "blur" }],
  icon: [{ required: true, message: "请上传分类图标", trigger: "blur" }],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      categoryPost(ruleForm).then((res) => {
        console.log(res);
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}));

// 初始化分类列表
const category = useCategory();
</script>
